#include "mainwindow.h"
#include "src/ui/loginform.h"
#include "src/ui/mainform.h"
#include <QApplication>
#include "src/wsim_client.h"
#include <QMessageBox>
#include <QDebug>
#include "src/myconfig.h"
#include <QDir>



int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    int ret=0;

    QDir filedir;
    QString filePath=QDir::homePath()+"/.wsim";
    if(!filedir.exists(filePath))
    {
        qDebug()<<QObject::tr("不存在该路径")<<endl;
        filedir.mkpath(filePath);
    }

    pConfig=new mycfg(filePath.toStdString()+"/wsim.cfg");

    std::string ip="59.230.57.45";
    int port=9753;
    if(argc==3)
    {
        ip=argv[1];
        std::string sport=argv[2];
        char *end;
        port=std::strtol(sport.c_str(),&end,10);

    }
    else
    {
            std::string key;
            std::string value;
            key="SERVER";
            value=pConfig->getValue( key);
            if(value.length()>0)
                ip=value;
            key="PORT";
            value="";
            value=pConfig->getValue( key);
            if(value.length()>0)
            {
                char *end;
                port=std::strtol(value.c_str(),&end,10);
            }
    }



    LoginForm l;
    l.setNetarg(QString::fromStdString(ip),port);
    //qDebug()<<mform;
    if(l.exec())
    {

        ip=l.getip().toStdString();
        port=l.getport();

        int fd=wsim_init(ip,port);
        if(fd<=0){
            QMessageBox::information(&l,"错误","连接服务器错误！",QMessageBox::Ok);
            return fd;
        }
        WSIM_client::setfd(fd);

        WSIM_client::setPageSize(1024*24);
        MainForm *mform=new MainForm(fd);

        QString loginname=l.getLoginname();
        mform->setNickname(loginname);
        WSIM_client::join(loginname.toStdString(),l.getPassword().toStdString());
        WSIM_client::hi();

        mform->show();
        WSIM_client::readUserInfo(loginname.toStdString());
        WSIM_client::readClients();

        pConfig->setValue("SERVER",ip);
        pConfig->setValue("PORT",std::to_string(port));



        ret= a.exec();

    }
    pConfig->WriteConfig();
    delete(pConfig);
    return ret;
}
